package com.supreme.omsserver.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.supreme.omsserver.config.props.CaffeineProps;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Configuration
public class CaffeineConfig {

    @Resource
    private CaffeineProps caffeineProps;

    @Bean(value = "caffeineCache")
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                .initialCapacity(caffeineProps.getCapacity())
                .maximumSize(caffeineProps.getMaxSize())
                .expireAfterWrite(caffeineProps.getExpireDuration(), TimeUnit.MINUTES)
                .build();
    }

    @Bean(value = "caffeineCacheItem")
    public <TV> Cache<String, TV> caffeineCacheItem() {
        return Caffeine.newBuilder()
                .initialCapacity(caffeineProps.getCapacity())
                .maximumSize(caffeineProps.getMaxSize())
                .expireAfterWrite(caffeineProps.getExpireDuration(), TimeUnit.MINUTES)
                .build();
    }

    @Bean(value = "caffeineCacheList")
    public <TV> Cache<String, List<TV>> caffeineCacheList() {
        return Caffeine.newBuilder()
                .initialCapacity(caffeineProps.getCapacity())
                .maximumSize(caffeineProps.getMaxSize())
                .expireAfterWrite(caffeineProps.getExpireDuration(), TimeUnit.HOURS)
                .build();
    }

    @Bean(value = "caffeineCacheHash")
    public <TV> Cache<String, Map<String, TV>> caffeineCacheHash() {
        return Caffeine.newBuilder()
                .initialCapacity(caffeineProps.getCapacity())
                .maximumSize(caffeineProps.getMaxSize())
                .expireAfterWrite(caffeineProps.getExpireDuration(), TimeUnit.HOURS)
                .build();
    }
}
